<template>
  <el-drawer
    v-model="visible"
    :title="isEdit ? '编辑用户' : '新增用户'"
    size="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="drawer-form"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" placeholder="请输入用户名" :disabled="isEdit" />
      </el-form-item>

      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.name" placeholder="请输入姓名" />
      </el-form-item>

      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入手机号" />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱" />
      </el-form-item>

      <el-form-item label="所属部门" prop="departmentIds">
        <el-tree-select
          v-model="form.departmentIds"
          :data="deptOptions"
          :props="{ label: 'name', value: 'id' }"
          placeholder="请选择所属部门"
          multiple
          clearable
          class="flex-1"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :value="0">待激活</el-radio>
          <el-radio :value="1">正常</el-radio>
          <el-radio :value="2" :disabled="!isEdit">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="drawer-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, reactive, watch, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { userApi } from '@/api/userApi'
import { departmentApi } from '@/api/departmentApi'

const emit = defineEmits(['update:modelValue', 'success'])

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  editData: {
    type: Object,
    default: () => null
  }
})

const visible = ref(false)
const loading = ref(false)
const formRef = ref(null)
const deptOptions = ref([])

// 表单数据
const form = reactive({
  username: '',
  name: '',
  phone: '',
  email: '',
  departmentIds: [],
  status: 0  // 默认为待激活状态
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 20, message: '长度在 4 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  departmentIds: [
    { required: true, message: '请选择所属部门', trigger: 'change' }
  ]
}

// 计算是否为编辑模式
const isEdit = computed(() => Boolean(props.editData))

// 监听抽屉显示状态
watch(() => props.modelValue, (val) => {
  visible.value = val
})

// 监听内部显示状态
watch(() => visible.value, (val) => {
  emit('update:modelValue', val)
  if (!val) {
    // 关闭时重置表单
    formRef.value?.resetFields()
    // 重置为初始状态
    Object.assign(form, {
      username: '',
      name: '',
      phone: '',
      email: '',
      departmentIds: [],
      status: 0  // 重置为待激活状态
    })
  }
})

// 监听编辑数据
watch(() => props.editData, (val) => {
  if (val) {
    const formData = { ...val }
    if (val.departments?.length) {
      formData.departmentIds = val.departments.map(dept => dept.id)
    }
    Object.assign(form, formData)
  } else {
    // 新建用户时重置为待激活状态
    form.status = 0
  }
}, { immediate: true })

// 获取部门树数据
const loadDeptOptions = async () => {
  try {
    const res = await departmentApi.getDepartmentTree()
    if (res.code === 200) {
      deptOptions.value = res.data
    }
  } catch (error) {
    console.error('获取部门树失败:', error)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    loading.value = true
    // 处理空字符串
    const formData = {
      ...form,
      email: form.email?.trim() || null,
      phone: form.phone?.trim() || null
    }
    
    const api = isEdit.value ? userApi.updateUser : userApi.createUser
    const params = isEdit.value ? [props.editData.id, formData] : [formData]
    
    const res = await api(...params)
    if (res.code === 200) {
      ElMessage.success(`${isEdit.value ? '更新' : '创建'}成功`)
      visible.value = false
      emit('success')
    } else {
      ElMessage.error(res.message || `${isEdit.value ? '更新' : '创建'}失败`)
    }
  } catch (error) {
    console.error(`${isEdit.value ? '更新' : '创建'}用户失败:`, error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  } finally {
    loading.value = false
  }
}

// 初始化
onMounted(() => {
  loadDeptOptions()
})
</script>

<style lang="scss" scoped>
.drawer-form {
  padding: 16px 20px;
  height: calc(100% - 120px);
  overflow-y: auto;
}

.drawer-footer {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 16px 20px;
  background: #fff;
  border-top: 1px solid #e6e6e6;
  text-align: right;
}

:deep(.el-drawer__body) {
  height: 100%;
  padding: 0;
  overflow: hidden;
}

:deep(.el-drawer__header) {
  margin-bottom: 0;
  padding: 16px 20px;
  border-bottom: 1px solid #e6e6e6;
}

:deep(.el-form-item:last-child) {
  margin-bottom: 0;
}

:deep(.el-tree-select) {
  width: 100%;
}
</style> 